
package cartagows.wsframework.wssecurity.policy.builders;

import java.util.Iterator;
import java.util.List;

import javax.xml.namespace.QName;

import org.apache.axiom.om.OMElement;
import org.apache.neethi.Assertion;
import org.apache.neethi.AssertionBuilderFactory;
import org.apache.neethi.Policy;
import org.apache.neethi.PolicyEngine;
import org.apache.neethi.builders.AssertionBuilder;
import org.apache.neethi.builders.xml.XmlPrimtiveAssertion;

import cartagows.wsframework.wssecurity.policy.SP11Constants;
import cartagows.wsframework.wssecurity.policy.SPConstants;
import cartagows.wsframework.wssecurity.policy.model.ProtectionToken;
import cartagows.wsframework.wssecurity.policy.model.Token;

public class ProtectionTokenBuilder implements AssertionBuilder {

    public Assertion build(OMElement element, AssertionBuilderFactory factory) throws IllegalArgumentException {
        ProtectionToken protectionToken = new ProtectionToken(SPConstants.SP_V11);
        
        Policy policy = PolicyEngine.getPolicy(element.getFirstElement());
        policy = (Policy) policy.normalize(false);
        
        for (Iterator iterator = policy.getAlternatives(); iterator.hasNext();) {
            processAlternative((List) iterator.next(), protectionToken);
            break; // since there should be only one alternative ..
        }
        
        return protectionToken;
    }
        
    public QName[] getKnownElements() {
        return new QName[] {SP11Constants.PROTECTION_TOKEN};
    }

    private void processAlternative(List assertions, ProtectionToken parent) {
        Assertion token = (Assertion) assertions.get(0);
        
        if(token.getName().getLocalPart().equals("UsernameToken")){
        	UsernameTokenBuilder utb = new UsernameTokenBuilder();
        	token = utb.build(((XmlPrimtiveAssertion ) token).getValue(), null);
        	
        }
        if(token.getName().getLocalPart().equals("X509Token")){
        	X509TokenBuilder xtb = new X509TokenBuilder();
        	token = xtb.build(((XmlPrimtiveAssertion ) token).getValue(), null);
        	
        }
        if (token instanceof Token) {
            parent.setToken((Token) token);
        }
    }
}
